<template>
  <a-modal title="" width="70%" :visible="visible" @ok="submit" @cancel="cancelAdd">
    <a-form :form="form">
      <a-form-item label="标题">
        <a-input v-decorator="['name', { rules: [{ required: true, message: '请输入' }] }]" placeholder="" />
      </a-form-item>
      <a-form-item label="内容">
        <div id="toolbar-container-addGoods"></div>
        <div id="editor-addGoods"></div>
      </a-form-item>
      <a-form-item label="图片">
        <!-- <a-upload class="swiperUpload" :action="aliOssConfig.uploadUrl" :data="formData"
					@change="handleImgChange">
					<div v-if="fileList.length < 8">
						<a-icon type="plus" />
						<div class="ant-upload-text">添加</div>
					</div>
				</a-upload> -->
        <!--  <a-upload class="swiperUpload" :action="aliOssConfig.uploadUrl" :data="formData" list-type="picture-card"
          :file-list="fileList" :before-upload="beforeUpload" @change="handleImgChange">
          <div v-if="fileList.length < 8">
            <a-icon type="plus" />
            <div class="ant-upload-text">添加</div>
          </div>
        </a-upload> -->
        <uploadBox ref='upload' @success='uploadSuccess'></uploadBox>
      </a-form-item>
      <a-form-item label="视频">
        <a-upload class="swiperUpload" :action="aliOssConfig.uploadUrl" :data="formData" list-type="picture-card"
          :file-list="fileListVideo" :before-upload="beforeUploadVideo" :show-upload-list="false"
          @change="handleVideoChange">
          <!-- <div v-if="fileListVideo.length < 1">
						<a-icon type="plus" />
						<div class="ant-upload-text">添加</div>
					</div> -->
          <img v-if="videoUrl!=''" style="width: 100px;"
            :src="videoUrl+'?x-oss-process=video/snapshot,t_3000,f_jpg,w_0,h_0,m_fast,ar_auto'" alt="avatar" />
          <div v-else>
            <loading-outlined v-if="loading"></loading-outlined>
            <!-- <plus-outlined v-else></plus-outlined> -->
            <div class="ant-upload-text">Upload</div>
          </div>
        </a-upload>
        <!-- <a-upload v-model:file-list="fileListVideo"  :action="aliOssConfig.uploadUrl"
					:data="formData" list-type="picture-card" class="avatar-uploader" :show-upload-list="false"
					@change="handleVideoChange">
					<img v-if="videoUrl" :src="videoUrl" alt="avatar" />
					<div v-else>
						<loading-outlined v-if="loading"></loading-outlined>
						<plus-outlined v-else></plus-outlined>
						<div class="ant-upload-text">Upload</div>
					</div>
				</a-upload> -->
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
  import MyUploadAdapter from '@/utils/MyUploadAdapter.js'
  import DecoupledEditor from '@ckeditor/ckeditor5-build-decoupled-document'
  import '@ckeditor/ckeditor5-build-decoupled-document/build/translations/zh-cn'
  import uploadBox from '@/components/obsUpload/obsUploadList'
  import {
    newsAdd,
    newsUpdate
  } from '@/api/news'
  import {
    getFormData
  } from '@/utils/aliOss/aliossUpload.js'
  import aliOssConfig from '@/utils/aliOss/config'
  const formItemLayout = {
    labelCol: {
      span: 4
    },
    wrapperCol: {
      span: 8
    },
  };
  const formTailLayout = {
    labelCol: {
      span: 4
    },
    wrapperCol: {
      span: 8,
      offset: 4
    },
  };

  export default {
    components: {
      uploadBox
    },
    props: {
      visible: {
        type: Boolean,
        required: true,
      }
    },
    data() {
      return {
        fileListVideo: [],
        fileList: [],
        checkNick: false,
        formItemLayout,
        formTailLayout,
        form: this.$form.createForm(this),
        loading: false,
        videoUrl: '',
        formData: {},
        aliOssConfig: aliOssConfig,
        id: 0,
        updateflag: false,
        editor: ''
      };
    },
    created() {
      var that = this
      this.$watch('visible', (e) => {
        if (e) {
          if (!that.editor) {
            this.$nextTick(function() {
              setTimeout(function() {
                that.initEditor()
              }, 100)
            })
          }
        }
      })
    },
    methods: {
      uploadSuccess(v) {
        this.fileList = v
        let values = this.form.getFieldsValue();
        this.form.setFieldsValue(values);
      },
      beforeUploadVideo(file) {
        this.formData = getFormData()
        console.log(file.type)
        const isVideo = file.type === 'video/mp4'
        if (!isVideo) {
          this.$message.error('请上传视频类型文件!')
        }
        const isLt2M = file.size / 1024 / 1024 < 100
        if (!isLt2M) {
          this.$message.error('图片最大体积为100MB!')
        }
        return isVideo && isLt2M
      },
      beforeUpload(file) {
        this.formData = getFormData()
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isJpgOrPng) {
          this.$message.error('请上传图片类型文件!')
        }
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          this.$message.error('图片最大体积为2MB!')
        }
        return isJpgOrPng && isLt2M
      },
      handleVideoChange(info) {
        if (info.file.status == "removed") {
          this.videoUrl = ''
        } else {
          var that = this;
          if (info.file.status == "done") {
            console.log(that.aliOssConfig.uploadUrl + '/' + that.formData.key)
            info.fileList[info.fileList.length - 1].url = that.aliOssConfig.uploadUrl + '/' + that.formData
              .key;
          }
          this.videoUrl = that.aliOssConfig.uploadUrl + '/' + that.formData
            .key;
        }
        this.fileListVideo = [info.fileList.slice(-1)[0]]

      },
      handleImgChange(info) {
        if (info.file.status == "removed") {

        } else {
          var that = this;
          const isJpgOrPng = info.file.type === 'image/jpeg' || info.file.type === 'image/png'
          if (!isJpgOrPng) {
            this.$message.error('您只能上传图片类型文件!')
            return
          }
          const isLt2M = info.file.size / 1024 / 1024 < 1

          if (!isLt2M) {
            this.$message.error('图片必须小于 1MB!')
            return
          }
          if (info.file.status == "done") {
            var url = that.aliOssConfig.uploadUrl + '/' + that.formData.key;
            var img = new Image();
            // 图片地址
            img.src = url
            let res = {}
            img.onload = function() {
              url = url + '?width=' + img.width + '&height=' + img.height
              info.fileList[info.fileList.length - 1].url = url
              console.log(url)
            }

          }
        }
        this.fileList = info.fileList
      },
      initEditor() {
        var that = this
        DecoupledEditor.create(document.querySelector('#editor-addGoods'), {
            language: 'zh-cn',
            toolbar: {
              items: [
                'heading',
                '|',
                'fontfamily',
                'fontsize',
                '|',
                'alignment',
                '|',
                'fontColor',
                'fontBackgroundColor',
                '|',
                'bold',
                'italic',
                'strikethrough',
                'underline',
                'subscript',
                'superscript',
                '|',
                'link',
                '|',
                'outdent',
                'indent',
                '|',
                'bulletedList',
                'numberedList',
                'todoList',
                '|',
                'code',
                'codeBlock',
                '|',
                'insertTable',
                '|',
                'uploadImage',
                'blockQuote',
                '|',
                'undo',
                'redo',
              ],
              shouldNotGroupWhenFull: true,
            },
          })
          .then((editor) => {
            that.editor = editor
            const toolbarContainer = document.querySelector('#toolbar-container-addGoods')
            toolbarContainer.appendChild(editor.ui.view.toolbar.element)
            editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
              return new MyUploadAdapter(loader)
            }
          })
          .catch((error) => {
            console.error(error)
          })
      },

      cancelAdd() {
        this.updateflag = false
        this.$emit('cancel', true)
        this.form.resetFields()
        this.videoUrl = ''
        this.$refs.upload.fileList = []
      },
      initAdd() {
        this.fileList = []
        this.fileListVideo = []
        this.videoUrl = ''
      },
      setUpdate(formValue) {
        this.updateflag = true
        this.id = formValue.id
        this.form.setFieldsValue({
          ...formValue
        })
        var that = this
        var imagesArray = []
        if (formValue.images !== '') {
          imagesArray = formValue.images.split(',')
          var imagesNewArray = []
          var bannerCurrrent = -1
          for (var i = 0; i < imagesArray.length; i++) {
            imagesNewArray.push({
              url: imagesArray[i],
              name: new Date().getTime() + '.png',
              status: 'done',
              uid: (((1 + Math.random()) * 0x10000) | 0).toString(16),
            })
          }
          that.fileList = imagesNewArray
          this.$refs.upload.fileList = imagesNewArray
        }
        if (formValue.video !== '') {
          imagesArray = formValue.video
          var imagesNewArray = []
          imagesNewArray.push({
            url: imagesArray,
            name: new Date().getTime() + '.png',
            status: 'done',
            uid: (((1 + Math.random()) * 0x10000) | 0).toString(16),
          })
          this.videoUrl = formValue.video
          this.fileListVideo = imagesNewArray
        }
        if (this.editor) {
          this.editor.setData(formValue.content)
        } else {
          setTimeout(() => {
            this.editor.setData(formValue.content)
          }, 1000)
        }
      },
      submit() {
        var that = this
        const {
          form: {
            validateFields
          },
        } = this

        validateFields((errors, values) => {
          if (!errors) {
            var editorData = this.editor.getData();
            if (!editorData) {
              this.$message.warning('请编辑内容');
              return false
            }
            if (this.fileList.length == 0 && this.videoUrl == '') {
              this.$message.warning('请上传图片或视频');
              return false
            }
            values.content = editorData

            var imglist = []
            for (var i = 0; i < this.fileList.length; i++) {
              imglist.push(that.fileList[i].url);
            }
            values.images = imglist.join(',');
            values.video = this.videoUrl

            if (this.updateflag) {
              values.id = this.id
              newsUpdate({
                ...values,
              }).then((res) => {
                if (res.code == 0) {
                  that.form.resetFields()
                  this.$refs.upload.fileList = []
                  that.$emit('ok')
                }
              })
            } else {
              newsAdd({
                ...values,
              }).then((res) => {
                if (res.code == 0) {
                  that.form.resetFields()
                  this.$refs.upload.fileList = []
                  that.$emit('ok')
                }
              })
            }
          }
        })
      },
      beforeUpload(file) {
        this.formData = getFormData()
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isJpgOrPng) {
          this.$message.error('请上传图片类型文件!')
        }
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          this.$message.error('图片最大体积为2MB!')
        }
        return isJpgOrPng && isLt2M
      },
    },
  };
</script>
<style>
  #editor-addGoods {
    min-height: 300px;
    max-height: 700px;
    overflow-y: auto;
    overflow-wrap: anywhere;
    word-break: break-word;
    background-color: #f9f9f9;
    color: #001234;
  }
</style>